package cn.fl.insroute.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.fl.insroute.service.IInsRouteBscInfoService;
import cn.fl.insroute.vo.InsRouteBscInfoVO;
import cn.fl.preinsroute.condition.PreRoutePrdInfoQC;
import cn.fl.preinsroute.constant.PreRouteConstant;
import cn.fl.preinsroute.service.IPreRoutePrdInfoService;
import cn.fl.preinsroute.vo.PreRouteInsResVO;
import cn.fl.preinsroute.vo.PreRoutePrdInfoVO;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.vo.PrjBscInfoVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.fl.insroute.condition.InsRoutePrdInfoQC;
import cn.fl.insroute.service.IInsRoutePrdInfoService;
import cn.fl.insroute.vo.InsRoutePrdInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description: 路由车辆信息 控制层
 */
@Controller
@RequestMapping("/insroute/insRoutePrdInfo")
public class InsRoutePrdInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InsRoutePrdInfoController.class);

	/**
	 * InsRoutePrdInfo 服务层BEAN
	 */
	@Autowired
	private IInsRoutePrdInfoService insRoutePrdInfoService;

	@Autowired
	private IInsRouteBscInfoService insRouteBscInfoService;

	@Autowired
	private IPrjBscInfoService prjBscInfoService;

	@Autowired
	private IPreRoutePrdInfoService preRoutePrdInfoService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("insroute/insRoutePrdInfo/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("insroute/insRoutePrdInfo/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		InsRoutePrdInfoQC qc = new InsRoutePrdInfoQC();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = new Pager();//this.insRoutePrdInfoService.searchListPage(page);
		List<InsRoutePrdInfoVO> list = (List<InsRoutePrdInfoVO>) pager.getResultList();
		ListPageVO<InsRoutePrdInfoVO> listPage = new ListPageVO<InsRoutePrdInfoVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 初始化路由车辆数据
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initRoutePrdInfo.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initRoutePrdInfo(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"initRoutePrdInfo","初始化路由车辆数据.请求时间：" + startTm + "-请求参数：" + this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName());
		String prjId = request.getParameter("prjId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "初始化路由车辆数据成功");
		ListPageVO<InsRoutePrdInfoVO> listPage = null;
		try {
			if(StringUtils.isEmpty(prjId)){
				BaseLogUtils.info(logger,"initRoutePrdInfo","项目ID为空");
				throw new BaseException("项目ID为空");
			}
			PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
			Long preResId = prjBscInfoVO.getPreResId();
			InsRouteBscInfoVO insRouteBscInfoVO = this.insRouteBscInfoService.searchListByPrjId(Long.valueOf(prjId));
			BaseLogUtils.info(logger,"initRoutePrdInfo","初始化路由车辆数据.查询路由数据结果insRouteBscInfoVO：" + JSON.toJSONString(insRouteBscInfoVO),CurrentThreadContext.getCurrentUserName());
			List<InsRoutePrdInfoVO> insRoutePrdInfoVOList = new ArrayList<InsRoutePrdInfoVO>();
			if(insRouteBscInfoVO != null){
				insRoutePrdInfoVOList = insRouteBscInfoVO.getInsRoutePrdInfoVOList();
				for (InsRoutePrdInfoVO insRoutePrdInfoVO : insRoutePrdInfoVOList) {
					if(insRoutePrdInfoVO.getGuidePc() == null){
						throw new BaseException("设备信息异常");
					}
					insRoutePrdInfoVO.setGuidePc( DecimalUtils.convertFenToYuan(insRoutePrdInfoVO.getGuidePc().longValue()));
					insRoutePrdInfoVO.setMediationFeeAmt(DecimalUtils.convertFenToYuan(insRoutePrdInfoVO.getMediationFeeAmt()).longValue()*insRoutePrdInfoVO.getPrdQty());
				}
			}else{
				if(preResId != null){
					PreRoutePrdInfoQC preRoutePrdInfoQC = new PreRoutePrdInfoQC();
					preRoutePrdInfoQC.setResId(Long.valueOf(preResId));
					List<PreRoutePrdInfoVO> preRoutePrdInfoVOS = this.preRoutePrdInfoService.searchList(preRoutePrdInfoQC);
					BaseLogUtils.info(logger,"initRoutePrdInfo","初始化路由车辆数据.查询预筛选信息preRoutePrdInfoVOS：" + JSON.toJSONString(preRoutePrdInfoVOS),CurrentThreadContext.getCurrentUserName());
					if(CollectionUtils.isEmpty(preRoutePrdInfoVOS)){
						throw new BaseException("预筛选信息获取异常");
					}
					for (PreRoutePrdInfoVO preRoutePrdInfoVO : preRoutePrdInfoVOS) {
						InsRoutePrdInfoVO insRoutePrdInfoVO = new InsRoutePrdInfoVO();
						insRoutePrdInfoVO.setPrjId(Long.valueOf(prjId));
						insRoutePrdInfoVO.setPrdTypCd(preRoutePrdInfoVO.getPrdTypCd());
						insRoutePrdInfoVO.setGuidePc(Double.valueOf(preRoutePrdInfoVO.getGuidePc()));
						insRoutePrdInfoVO.setBrId(preRoutePrdInfoVO.getBrId());
						insRoutePrdInfoVO.setBrCd(preRoutePrdInfoVO.getBrCd());
						insRoutePrdInfoVO.setModelId(preRoutePrdInfoVO.getModelId());
						insRoutePrdInfoVO.setModelNm(preRoutePrdInfoVO.getModelNm());
						insRoutePrdInfoVO.setPrdId(preRoutePrdInfoVO.getPrdId());
						insRoutePrdInfoVO.setPrdNm(preRoutePrdInfoVO.getPrdNm());
						insRoutePrdInfoVO.setPrdQty(BaseConstant.IS_YESNO_YES);
						insRoutePrdInfoVO.setMediationFeeAmt(preRoutePrdInfoVO.getMediationFeeAmt());
						insRoutePrdInfoVOList.add(insRoutePrdInfoVO);
					}
					BaseLogUtils.info(logger,"initRoutePrdInfo","初始化路由车辆数据.查询预筛选信息insRoutePrdInfoVOList：" + JSON.toJSONString(insRoutePrdInfoVOList),CurrentThreadContext.getCurrentUserName());
				}
			}
			if(CollectionUtils.isNotEmpty(insRoutePrdInfoVOList)){
				List<SysDictionaryDTO> cvmList = this.sysDictionaryApiService.searchGroup(PreRouteConstant.CVM_SYS_CD, PreRouteConstant.SYS_ORG,PreRouteConstant.CODE_PRD_TYP_CD);
				for (InsRoutePrdInfoVO insRoutePrdInfoVO : insRoutePrdInfoVOList) {
					for (SysDictionaryDTO sysDictionaryDTO : cvmList) {
						String code = sysDictionaryDTO.getCode();
						Integer codeLvl = sysDictionaryDTO.getCodeLvl();
						String codeAttr1 = sysDictionaryDTO.getCodeAttr1();
						if(codeLvl != null && StringUtils.isNotEmpty(codeAttr1) && insRoutePrdInfoVO.getPrdId().equals(Long.valueOf(code)) && codeLvl.equals(PreRouteConstant.PRE_ROUTE_PRD_LVL)){
							insRoutePrdInfoVO.setPrdCd(codeAttr1);
							break;
						}
					}
				}
			}
			if(CollectionUtils.isNotEmpty(insRoutePrdInfoVOList)){
				listPage = new ListPageVO<InsRoutePrdInfoVO>(insRoutePrdInfoVOList, insRoutePrdInfoVOList.size());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "initRoutePrdInfo", "初始化路由车辆数据.异常" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "initRoutePrdInfo", "初始化路由车辆数据.异常", CurrentThreadContext.getCurrentUserName());
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"initRoutePrdInfo","初始化路由车辆数据.返回结果：" + JSON.toJSONString(listPage) + "-耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}


	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.insRoutePrdInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			InsRoutePrdInfoVO vo = this.insRoutePrdInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		InsRoutePrdInfoVO entity = null;
		try {
			entity = new InsRoutePrdInfoVO();
			//TODO ADD PARAM
			Long id = this.insRoutePrdInfoService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		InsRoutePrdInfoVO entity = null;
		try {
			entity = new InsRoutePrdInfoVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.insRoutePrdInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

